<template>
	<div class="role-edit-container" v-loading="loading">
		<!-- 主内容区 -->
		<div class="main-content">
			<!-- 左侧表单区域 -->
			<div class="form-container">
				<h2 class="section-title">修改用户角色</h2>

				<el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="120px">
					<!-- 用户信息 -->
					<el-form-item label="用户ID" prop="userId">
						<el-input v-model="form.userId" disabled />
					</el-form-item>

					<el-form-item label="用户名" prop="username">
						<el-input v-model="form.username" disabled />
					</el-form-item>

					<!-- 当前角色 -->
					<el-form-item label="当前角色" prop="currentRole">
						<el-input v-model="form.currentRole" disabled />
					</el-form-item>

					<!-- 新角色选择 -->
					<el-form-item label="新角色" prop="newRoleId" required>
						<el-select v-model="form.newRoleId" placeholder="请选择新角色" style="width: 100%">
							<el-option v-for="role in roleOptions" :key="role.id" :label="role.roleName"
								:value="role.id" />
						</el-select>
					</el-form-item>
				</el-form>
			</div>

			<!-- 右侧预览区域 -->
			<div class="preview-container">
				<h2 class="section-title">角色变更预览</h2>

				<div class="preview-details">
					<h3>用户信息</h3>
					<ul>
						<li><el-icon>
								<User />
							</el-icon> 用户ID: {{ form.userId || "未设置" }}</li>
						<li><el-icon>
								<User />
							</el-icon> 用户名: {{ form.username || "未设置" }}</li>
					</ul>

					<div class="role-change">
						<h4>角色变更</h4>
						<div class="change-item">
							<span class="old-role">{{ form.currentRole || "无角色" }}</span>
							<el-icon>
								<Right />
							</el-icon>
							<span class="new-role">{{ getRoleName(form.newRoleId) || "请选择新角色" }}</span>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部操作栏 -->
		<div class="bottom-bar">
			<el-button @click="handleCancel">返回</el-button>
			<div class="right-buttons">
				<el-button type="primary" @click="handleSubmit">确认修改</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'UserRoleEditView',
	};
</script>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue";
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		User,
		Right
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		getRole
	} from '@/api/role.js'
	import {
		updateRoleUser
	} from '@/api/role.js'
	import {
		getUserinfo
	} from '@/api/userManager.js'

	const router = useRouter()
	const route = useRoute()
	const userId = route.params.id // 用户ID
	const loading = ref(false)

	/**
	 * 表单数据
	 */
	const form = ref({
		userId: "",
		username: "",
		currentRole: "",
		currentRoleId: "",
		newRoleId: ""
	});

	/**
	 * 角色选项
	 */
	const roleOptions = ref([]);

	/**
	 * 表单校验规则
	 */
	const rules = {
		newRoleId: [{
			required: true,
			message: '请选择新角色',
			trigger: 'change'
		}]
	};

	/**
	 * 获取角色名称
	 */
	const getRoleName = (roleId) => {
		const role = roleOptions.value.find(item => item.id === roleId);
		return role ? role.roleName : "";
	};

	/**
	 * 获取用户信息和角色列表
	 */
	const fetchData = async () => {
		loading.value = true;
		try {
			// 获取角色列表
			const rolesRes = await getRole();
			if (rolesRes.code === 200) {
				roleOptions.value = rolesRes.data;
			}

			// 获取用户信息
			const userRes = await getUserinfo(userId);
			if (userRes.code === 200) {
				form.value.userId = userRes.data.id;
				form.value.username = userRes.data.username;
				form.value.currentRole = userRes.data.roleName;
				form.value.currentRoleId = userRes.data.roleId;
				// 默认选中当前角色
				form.value.newRoleId = userRes.data.roleId;
			}
		} catch (error) {
			ElMessage.error('获取数据失败');
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 提交修改
	 */
	const handleSubmit = async () => {
		try {
			// 验证表单
			await formRef.value.validate();

			// 检查是否选择了新角色
			if (!form.value.newRoleId) {
				ElMessage.warning('请选择新角色');
				return;
			}

			// 检查是否和当前角色相同
			if (form.value.newRoleId === form.value.currentRoleId) {
				ElMessage.warning('新角色与当前角色相同，无需修改');
				return;
			}

			// 确认对话框
			await ElMessageBox.confirm(
				`确定将用户【${form.value.username}】的角色从【${form.value.currentRole}】修改为【${getRoleName(form.value.newRoleId)}】吗？`,
				'确认修改', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			);

			// 提交修改
			const res = await updateRoleUser({
				userId: form.value.userId,
				newRoleId: form.value.newRoleId
			});

			if (res.code === 204) {
				ElMessage.success('角色修改成功');
				fetchData();
			} else {
				ElMessage.error(res.message || '角色修改失败');
			}
		} catch (error) {
			if (error !== 'cancel') {
				console.error('提交失败:', error);
				ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
			}
		}
	};

	/**
	 * 取消编辑
	 */
	const handleCancel = () => {
		ElMessageBox.confirm("确定放弃当前编辑的内容吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
			.then(() => {
				ElMessage.info("已取消编辑");
				router.back();
			})
			.catch(() => {});
	};

	const formRef = ref(null);

	onMounted(() => {
		if (userId) {
			fetchData();
		} else {
			ElMessage.error('无效的用户ID');
			router.back();
		}
	});
</script>

<style scoped>
	.role-edit-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding: 20px;
		height: 95%;
		min-height: 0;
		overflow-y: auto;
	}

	.section-title {
		font-size: 1.25rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	.main-content {
		display: flex;
		gap: 20px;
		flex-wrap: wrap;
	}

	.form-container {
		flex: 1;
		min-width: 400px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
	}

	.preview-container {
		flex: 1;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 20px;
	}

	.bottom-bar {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-buttons {
		display: flex;
		gap: 10px;
	}

	.preview-details h3 {
		font-size: 1.1rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.preview-details ul {
		list-style: none;
		padding: 0;
		margin-bottom: 1.5rem;
	}

	.preview-details li {
		margin-bottom: 0.75rem;
		color: #6b7280;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.role-change {
		margin-top: 20px;
	}

	.role-change h4 {
		font-size: 0.875rem;
		font-weight: 500;
		color: #4b5563;
		margin-bottom: 0.5rem;
	}

	.change-item {
		display: flex;
		align-items: center;
		gap: 15px;
		margin-top: 10px;
		padding: 10px;
		background-color: #f3f4f6;
		border-radius: 4px;
	}

	.old-role {
		color: #f56c6c;
		font-weight: 500;
	}

	.new-role {
		color: #67c23a;
		font-weight: 500;
	}
</style>